package org.keyroy.map.core.manages;

import java.io.File;
import java.util.List;

import org.keyroy.map.core.Map;
import org.keyroy.mapEditor.ui.beans.FileUtil;

public class Project {
	public static final String MAP_FOLDER = "maps";
	public static final String RESOURCE_FOLDER = "res";

	private File file;

	public Project() {
		MapManage.reset();
		ResourceManage.reset();
	}

	public Project(File file) {
		this();
		this.file = file;

		loadResources();
		loadMaps();
	}

	public void loadResources() {
		try {
			File sourceFile = new File(getResourceFolder(), ResourceManage.class.getSimpleName() + ".xml");
			FileUtil.load(sourceFile, new ResourceManage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void loadMaps() {
		try {
			File mapFolder = getMapFolder();
			File[] files = mapFolder.listFiles();
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					try {
						Map map = (Map) FileUtil.load(files[i], Map.class);
						String mapName = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));
						map.setName(mapName);
						MapManage.add(map);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public File getFile() {
		return file;
	}

	public void remove(Map map) {
		MapManage.remove(map);
		File mapFolder = new File(file, MAP_FOLDER);
		File file = new File(mapFolder, map.getName());
		if (file.exists()) {
			deleteFolder(file);
		}
	}

	public void remove(Resource resource) {
		ResourceManage.remove(resource);
		saveResource();
	}

	public final File getMapFolder() {
		File mapFolder = new File(file, MAP_FOLDER);
		if (mapFolder.exists() == false) {
			mapFolder.mkdirs();
		}
		return mapFolder;
	}

	public final File getResourceFolder() {
		File mapFolder = new File(file, RESOURCE_FOLDER);
		if (mapFolder.exists() == false) {
			mapFolder.mkdirs();
		}
		return mapFolder;
	}

	public final void deleteFolder(File file) {
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				files[i].delete();
			} else {
				deleteFolder(files[i]);
			}
		}
		file.delete();
	}

	public void save() {
		List<Map> maps = MapManage.getMaps();
		for (int i = 0; i < maps.size(); i++) {
			save(maps.get(i));
		}
		saveResource();
	}

	public void saveResource() {
		File file = new File(getResourceFolder(), ResourceManage.class.getSimpleName() + ".xml");
		FileUtil.save(file, new ResourceManage());
	}

	public void save(Map map) {
		File mapFolder = getMapFolder();
		File file = new File(mapFolder, map.getName() + ".xml");
		FileUtil.save(file, map);
	}
}
